package com.taorenqi.business.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;


public class Encoder {
	/**
	 * @param value
	 *            string to be encoded
	 * @return encoded parameters string
	 */
	public static String encode(String value) {
	    String encoded = null;
	    try {
	        encoded = URLEncoder.encode(value, "UTF-8");
	    } catch (UnsupportedEncodingException ignore) {
	    }
	    StringBuffer buf = new StringBuffer(encoded.length());
	    char focus;
	    for (int i = 0; i < encoded.length(); i++) {
	        focus = encoded.charAt(i);
	        if (focus == '*') {
	            buf.append("%2A");
	        } else if (focus == '+') {
	            buf.append("%20");
	        } else if (focus == '%' && (i + 1) < encoded.length() && encoded.charAt(i + 1) == '7'
	                && encoded.charAt(i + 2) == 'E') {
	            buf.append('~');
	            i += 2;
	        } else {
	            buf.append(focus);
	        }
	    }
	    return buf.toString();
	}
	
	public static String getSign(Map<String, String> map){
		String value = "";
		String resultValue = "";
		if (map != null && map.size() > 0) {
			Map<String, String> resultMap = MapSort.sortMapByKey(map); //按Value进行排序
			for (Map.Entry<String, String> entry : resultMap.entrySet()) {
	            if(!entry.getValue().equals("")){
	            	value = value + entry.getKey() + "=" + entry.getValue() + "&";
	            }
	        }
			if(!value.equals("")){
				value = value + "key=" + SIGN_KEY;
				resultValue = AbMd5.MD5(value);
			}
		}
		return resultValue.toLowerCase();
	}
	public static String getSigns(Map<String, String> map){
		String value = "";
		String resultValue = "";
		if (map != null && map.size() > 0) {
			Map<String, String> resultMap = MapSort.sortMapByKey(map); //按Value进行排序
			for (Map.Entry<String, String> entry : resultMap.entrySet()) {
				value = value + entry.getKey() + "=" + entry.getValue() + "&";
			}
			if(!value.equals("")){
				value = value + "key=" + SIGN_KEY;
				resultValue = AbMd5.MD5(value);
			}
		}
		return resultValue.toLowerCase();
	}
	public static final String SIGN_KEY = "trqSellerApi20170110";
}

